package com.sgj.controller;

import com.alibaba.cola.statemachine.StateMachine;
import com.sgj.entity.Order;
import com.sgj.enums.OrderEventEnum;
import com.sgj.enums.OrderStatusEnum;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * @Author: Guoji Shen
 * @Date: 2023/11/6 13:26
 */
@RestController
public class OrderOperaController {

    @Autowired
    @Qualifier("orderOperaMachine")
    StateMachine<OrderStatusEnum, OrderEventEnum, Order> orderOperaMachine;

    /**
     * 场景1-用户关闭订单
     * @return {@link Boolean}
     */
    @RequestMapping("userclose")
    public Boolean userCloseOrder() {
        // 把订单状态改为关闭
        String machineId = orderOperaMachine.getMachineId();
        System.out.println(machineId);
        Order order = Order.builder().orderId(1).orderName("用户").orderStatusEnum(OrderStatusEnum.INIT).build();
        OrderStatusEnum orderStatusEnum = orderOperaMachine.fireEvent(OrderStatusEnum.INIT, OrderEventEnum.USER_CLOSE,
            order);
        System.out.println(orderStatusEnum.toString());
        return true;
    }

    /**
     * 场景2-管理员关闭订单
     * @return {@link Boolean}
     */
    @RequestMapping("adminClose")
    public Boolean adminCloseOrder() {
        // 把订单状态改为关闭
        Order order = Order.builder().orderId(1).orderName("后台操作人员")
            .orderStatusEnum(OrderStatusEnum.HAVE_BEEN_DELIVERY).build();
        OrderStatusEnum orderStatusEnum = orderOperaMachine.fireEvent(OrderStatusEnum.HAVE_BEEN_DELIVERY,
            OrderEventEnum.ADMIN_CLOSE, order);
        System.out.println(orderStatusEnum.toString());

        return true;
    }

    /**
     * 场景3-超时关闭订单
     * @return {@link Boolean}
     */
    @RequestMapping("overTimeclose")
    public Boolean overTimeCloseOrder() {
        // 把订单状态改为关闭
        Order order = Order.builder().orderId(1).orderName("超时了关闭订单")
            .orderStatusEnum(OrderStatusEnum.INIT).build();
        OrderStatusEnum orderStatusEnum = orderOperaMachine.fireEvent(OrderStatusEnum.INIT,
            OrderEventEnum.OVERTIME_CLOSE, order);
        System.out.println(orderStatusEnum.toString());
        return true;
    }

    /**
     * 场景4-检查错误关闭订单
     * @return {@link Boolean}
     */
    @RequestMapping("checkErrorClose")
    public Boolean checkErrorCloseOrder() {
        // 把订单状态改为关闭
        Order order = Order.builder().orderId(1).orderName("上级检查错误")
            .orderStatusEnum(OrderStatusEnum.WAITING_FOR_DELIVERY).build();
        OrderStatusEnum orderStatusEnum = orderOperaMachine.fireEvent(OrderStatusEnum.WAITING_FOR_DELIVERY,
            OrderEventEnum.CHECK_ERROR_CLOSE, order);
        System.out.println(orderStatusEnum.toString());
        return true;
    }
}